<template>
  <page-container title="登录" :showBack="true">
    <template v-slot:nav-left>
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
      </view>
    </template>
    <view class="login-container">
      <!-- 登录标题 -->
      <view class="title-section">
        <image src="/static/logo.png" mode="aspectFit" class="logo-icon"></image>
      </view>

      <!-- 登录表单 -->
      <view class="login-form">
        <!-- 手机号输入 -->
        <view class="input-group">
          <view class="input-label">
            <text class="label-text">手机号</text>
          </view>
          <view class="input-wrapper">
            <input class="phone-input" type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
          </view>
        </view>
        <!-- 密码输入 -->
        <view class="input-group" v-if="loginType === 'password'">
          <view class="input-label">
            <text class="label-text">密码</text>
          </view>
          <view class="input-wrapper">
            <input class="password-input" :password="!showPassword"  v-model="password"
              placeholder="请输入密码" />
            <view class="eye-btn" @click="togglePassword">
              <uni-icons class="eye-icon" :type="showPassword ? 'eye' : 'eye-slash'" size="20"
                color="#999999"></uni-icons>
            </view>
          </view>
        </view>

        <!-- 验证码输入 -->
        <view class="input-group" v-if="loginType === 'code'">
          <view class="input-label">
            <text class="label-text">验证码</text>
          </view>
          <view class="input-wrapper">
            <input class="code-input" type="number" v-model="verificationCode" placeholder="请输入验证码" maxlength="6" />
            <view class="code-btn" :class="{ 'countdown': countdown > 0 }" @click="sendCode">
              <text class="code-text">{{ codeText }}</text>
            </view>
          </view>
        </view>

        <view class="login-type-switch">
          <view class="login-type-switch-item" @click="handleRegister">
            <text class="login-type-switch-text">注册</text>
          </view>
          <!-- 当前登录方式提示 -->
          <view class="login-type-hint" @click="switchLoginType(loginType === 'password' ? 'code' : 'password')">
            <text class="hint-text">{{ loginType === 'password' ? '验证码' : '密码' }}登录</text>
          </view>
        </view>
        <!-- 登录按钮 -->
        <view class="login-btn" @click="handleLogin">
          <text class="login-text">登录</text>
        </view>

        <!-- 底部协议 -->
        <view class="agreement">
          <view class="agreement-item" @click="toggleAgreement">
            <view class="checkbox" :class="{ checked: isAgreed }">
              <text class="checkbox-text" v-if="isAgreed">
                <uni-icons type="checkmark" size="16" color="#fff"></uni-icons>
              </text>
            </view>
          </view>
          <text class="agreement-text">我已知晓</text>
          <text class="agreement-link" @click="openPrivacyPolicy">《隐私政策》</text>
          <text class="agreement-text">和</text>
          <text class="agreement-link" @click="openServiceAgreement">《注册和服务协议》</text>
        </view>
      </view>
    </view>
  </page-container>
</template>

<script>
import { validatePhone } from '../../utils/tools'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

export default {
  name: 'LoginPage',
  components: {
    uniIcons
  },
  data() {
    return {
      phone: '',
      password: '',
      verificationCode: '',
      loginType: 'password',
      showPassword: false,
      countdown: 0,
      timer: null,
      isAgreed: false
    }
  },
  computed: {
    codeText() {
      if (this.countdown > 0) {
        return `${this.countdown}s后重发`
      }
      return '获取验证码'
    }
  },
  methods: {
    goBack() {
      setTimeout(() => {
        uni.navigateBack()
      }, 100)
    },
    // 切换协议同意
    toggleAgreement() {
      this.isAgreed = !this.isAgreed
    },
    // 隐私政策
    openPrivacyPolicy() {
      uni.navigateTo({
        url: '/pages/login/privacyPolicy'
      })
    },
    // 注册和服务协议
    openServiceAgreement() {
      uni.navigateTo({
        url: '/pages/login/agreement'
      })
    },
    handleRegister() {
      uni.navigateTo({
        url: '/pages/login/registered'
      })
    },
    switchLoginType(type) {
      if (this.loginType === type) return

      this.loginType = type

      // 清空输入框
      if (type === 'password') {
        this.verificationCode = ''
        this.showPassword = false
      } else {
        this.password = ''
      }

    },
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    async sendCode() {
      if (this.countdown > 0) return

      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }

      // 使用全局请求验证手机号
      if (!validatePhone(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      try {
        let res = await this.$http.post('/applet/customer/sendSms', { cusPhone: this.phone, scene: 'LOGIN' })
        this.countdown = 60
        this.timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)

        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: '发送验证码失败，请重试',
          icon: 'none'
        })
      }
    },
    async handleLogin() {
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }

      if (!validatePhone(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }



      if (this.loginType === 'password') {
        if (!this.password) {
          uni.showToast({
            title: '请输入密码',
            icon: 'none'
          })
          return
        }
        // 密码最小位数：6 位，最大位数16位
        if (this.password.length < 6 || this.password.length > 16) {
          uni.showToast({
            title: '密码长度不能少于6位，不能大于16位',
            icon: 'none'
          })
          return
        }
        // 密码不能包含空格
        if (this.password.includes(' ')) {
          uni.showToast({
            title: '密码不能包含空格',
            icon: 'none'
          })
          return
        }
        // 密码 数字或字母
        if (!/^[a-zA-Z0-9]+$/.test(this.password)) {
          uni.showToast({
            title: '密码只能包含数字或字母',
            icon: 'none'
          })
          return
        }
        if (!this.isAgreed) {
          uni.showToast({
            title: '请先同意协议',
            icon: 'none'
          })
          return
        }
		let openId = uni.getStorageSync('openId');
        try {
          let api = '/applet/customer/login'
          let params = {
            cusPhone: this.phone,
            password: this.password,
			openId: uni.getStorageSync('openId') ? uni.getStorageSync('openId') : ''
          }
          const result = await this.$http.post(api, params)
          if (result.data.customerStatus === 'AUDITING') {
            uni.showModal({
              title: '提示',
              content: '注册用户待审核，请联系平台审核',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  return
                }
              }
            })
            return
          }
          uni.setStorageSync('customerInfo', result.data || {})
          // 保存token
          if (result.data && result.data.token) {
            uni.setStorageSync('token', result.data.token)
          }

          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/home/index'
            })
          }, 100)
        } catch (error) {
          console.log(1110, error);

          uni.showToast({
            title: error.msg || '登录失败，请检查手机号和密码',
            icon: 'none'
          })
        }
      } else {
        if (!this.verificationCode) {
          uni.showToast({
            title: '请输入验证码',
            icon: 'none'
          })
          return
        }
        // 验证码长度为6
        if (this.verificationCode.length !== 6) {
          uni.showToast({
            title: '请输入正确的6位验证码',
            icon: 'none'
          })
          return
        }
        if (!this.isAgreed) {
          uni.showToast({
            title: '请先同意协议',
            icon: 'none'
          })
          return
        }

        try {
          let api = '/applet/customer/smsLogin'
          let params = {
            cusPhone: this.phone,
            validCode: this.verificationCode,
            openId: uni.getStorageSync('openId') ? uni.getStorageSync('openId') : ''
          }

          const result = await this.$http.post(api, params)
          if (result.data.customerStatus === 'AUDITING') {
            uni.showModal({
              title: '提示',
              content: '注册用户待审核，请联系平台审核',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  return
                }
              }
            })
            return
          }
          uni.setStorageSync('customerInfo', result.data || {})
          // 保存token
          if (result.data && result.data.token) {
            uni.setStorageSync('token', result.data.token)
          }

          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/home/index'
            })
          }, 1000)
        } catch (error) {
          uni.showToast({
            title: error.msg || '登录失败，请检查手机号和验证码',
            icon: 'none'
          })
        }
      }
    }
  },
  onUnload() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/uni.scss';

.login-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 0;
}

.title-section {
  padding: 60rpx 0 100rpx 0;
  display: block;
  text-align: center;

  .logo-icon {
    width: 200rpx;
    height: 200rpx;
  }
}

.main-title {
  display: block;
  font-size: 48rpx;
  color: #0B1F20;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.sub-title {
  display: block;
  font-size: 28rpx;
  color: #666666;
}

.login-form {
  padding: 0 30rpx;
}

.input-group {
  margin-bottom: 40rpx;
  animation: fadeInUp 0.3s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-label {
  margin-bottom: 20rpx;
}

.label-text {
  font-size: 28rpx;
  color: #0B1F20;
  font-weight: 500;
}

.input-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 20rpx;
}

// .phone-prefix {
//   font-size: 28rpx;
//   color: #0B1F20;
//   margin-right: 20rpx;
// }

.phone-input,
.password-input,
.code-input {
  flex: 1;
  font-size: 28rpx;
  color: #0B1F20;
  border: none;
  background: transparent;
}

/* 去除输入框聚焦时的默认边框/高亮 */
.phone-input:focus,
.password-input:focus,
.code-input:focus {
  outline: none;
  box-shadow: none;
  border-color: transparent;
  -webkit-appearance: none;
  appearance: none;
}

/* H5 点击高亮取消 */
input {
  -webkit-tap-highlight-color: transparent;
}

.eye-btn {
  padding: 10rpx;
}

.eye-icon {
  font-size: 32rpx;
  color: #666666;
}

.code-btn {
  padding: 10rpx 20rpx;
  background-color: $uni-text-color-orange;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.code-btn:active {
  background-color: #e65100;
  transform: scale(0.95);
}

.code-text {
  font-size: 24rpx;
  color: #ffffff;
  transition: color 0.3s ease;
}

.code-btn.countdown {
  background-color: #cccccc;
}

.code-btn.countdown .code-text {
  color: #999999;
}

.login-type-switch {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40rpx;

  .login-type-switch-text {
    font-size: 28rpx;
    color: #999999;
  }

  .login-type-hint {
    text-align: right;
    margin-bottom: 30rpx;

    .hint-text {
      font-size: 28rpx;
      color: #999999;
    }

  }
}



.login-btn {
  background: $uni-text-color-orange;
  border-radius: 12rpx;
  padding: 30rpx;
  text-align: center;
  margin: 60rpx 0 40rpx;
}

.login-text {
  font-size: 32rpx;
  color: #ffffff;
  letter-spacing: 2rpx;
}

.agreement {
  margin-top: 60rpx;
  text-align: center;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.agreement-text {
  font-size: 24rpx;
  color: #999999;
}

.agreement-link {
  font-size: 24rpx;
  color: $uni-text-color-orange;
}

@media screen and (max-width: 750rpx) {
  .login-container {
    padding-bottom: 120rpx;
  }
}

.agreement-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-right: 20rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #d4af37;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 4rpx;
}

.checkbox.checked {
  background-color: #d4af37;
}

/* 备用勾选图标样式 */
.checkbox.checked::after {
  content: '';
  width: 18rpx;
  height: 10rpx;
  border: 2rpx solid #ffffff;
  border-top: none;
  border-right: none;
  transform: rotate(-45deg);
  margin-top: -6rpx;
}
</style>